package com.open.capacity.reimburse.controller;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.reimburse.excel.CarExcelModel;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import com.open.capacity.reimburse.entity.BaseCar;
import com.open.capacity.reimburse.service.BaseCarService;

import com.open.capacity.commons.PageResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 车辆
 *
 * @author
 * @email
 * @date 2021-03-01 10:14:42
 */
@RestController
@RequestMapping("cars")
@Api(tags = "车辆")
public class BaseCarController {

    @Autowired
    private BaseCarService baseCarService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = baseCarService.pageAll(params);
        return pageResult;
    }

    /**
     * 查询车辆tree
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('base_car:get/cars')")
    @ApiOperation(value = "查询tree")
    @GetMapping("/tree")
    public Result<List<TreeVo>> treeCars(@RequestParam(value = "parentId", defaultValue = "0") String parentId,
                                                @RequestParam(value = "status", defaultValue = "0") Integer status) {
        Map<String, Object> params = new HashMap<>();
        if (status > 0) {
            params.put("status", status);
        }
        List<BaseCar> cars = baseCarService.findAll(params);
        List<TreeVo> treeList = new TreeList();
        cars.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getLicensePlateNumber());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId("0");
            treeList.add(node);
        });

        return Result.succeed(treeList);
    }


    /**
     * 车辆使用记录
     */
    @RequestMapping("/history")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:list')")
    public PageResult history(@RequestParam Map<String, Object> params) {
        PageResult pageResult = baseCarService.pageHistory(params);
        return pageResult;
    }

    /**
     * 查询单条记录
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:list')")
    public Result findById(String id) {
        return Result.succeed(baseCarService.findById(id));
    }

    /**
     * 保存
     */
    @RequestMapping("/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:save')")
    @LogAnnotation(module = "车辆记录", name = "保存")
    public Result save(@RequestBody @Valid BaseCar baseCar, String keyValue) {
        if (StringUtils.isEmpty(keyValue)) {
            baseCarService.save(baseCar);
        } else {
            baseCar.setId(keyValue);
            baseCarService.update(baseCar);
        }
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:delete')")
    @LogAnnotation(module = "车辆记录", name = "删除")
    public Result delete(@PathVariable String id) {
        baseCarService.delete(id);
        return Result.succeed("删除成功");
    }

    /**
     * 导入excel
     */
    @PostMapping("/importExcel")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:import')")
    public Result importExcel(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        int count = baseCarService.importExcel(multipartFile);
        return Result.succeed(count, "导入成功");
    }

    /**
     * 导出数据
     */
    @GetMapping("/exportExcel")
    @PreAuthorize("hasAnyAuthority('base_car:basecar:export')")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        List<BaseCar> list = baseCarService.findAll(params);

        List<CarExcelModel> result = list.stream().map(item -> {
            CarExcelModel model = new CarExcelModel();
            BeanUtils.copyProperties(item, model);
            return model;
        }).collect(Collectors.toList());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=car.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("车辆档案", "车辆档案列表"),
                CarExcelModel.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
